const express = require('express');
const { html: getPrettyHtml } = require('diff2html');
const simpleGit = require('simple-git');
const fs = require('fs');
const path = require('path');

const app = express();
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.urlencoded({ extended: false }));
app.use(express.json()); // 添加 JSON 解析中间件

// 导出评论为 CSV
app.post('/export', async (req, res) => {
  try {
    const { comments, repoPath } = req.body;
    
    if (!comments || !Array.isArray(comments)) {
      return res.status(400).json({ error: '无效的评论数据' });
    }

    // 获取 Git 用户名
    let gitUsername = '未知用户';
    if (repoPath && fs.existsSync(path.join(repoPath, '.git'))) {
      try {
        const git = simpleGit(repoPath);
        const config = await git.listConfig();
        gitUsername = config.all['user.name'] || config.all['user.email'] || '未知用户';
      } catch (e) {
        console.warn('获取 Git 用户名失败:', e.message);
      }
    }

    // 生成 CSV 内容
    const csvHeader = '评论日期,评论人,评论内容,代码位置\n';
    const csvRows = comments.map(comment => {
      const date = new Date(comment.id).toLocaleString('zh-CN');
      const location = `${comment.file} [${comment.startLine}${comment.startLine === comment.endLine ? '' : ' - ' + comment.endLine}]`;
      // 处理 CSV 中的特殊字符
      const escapedText = comment.text.replace(/"/g, '""');
      const escapedLocation = location.replace(/"/g, '""');
      return `"${date}","${gitUsername}","${escapedText}","${escapedLocation}"`;
    }).join('\n');

    const csvContent = csvHeader + csvRows;

    // 设置响应头
    res.setHeader('Content-Type', 'text/csv; charset=utf-8');
    res.setHeader('Content-Disposition', 'attachment; filename="comments.csv"');
    
    // 添加 BOM 以确保中文正确显示
    const bom = Buffer.from('\uFEFF');
    res.send(Buffer.concat([bom, Buffer.from(csvContent, 'utf8')]));

  } catch (error) {
    console.error('导出失败:', error);
    res.status(500).json({ error: '导出失败: ' + error.message });
  }
});

app.get('/', async (req, res) => {
  const repoPath = req.query.repoPath || '';
  const from     = req.query.from    || 'HEAD~1';
  const to       = req.query.to      || 'HEAD';

  let error = '';
  let diffHtml = '';

  if (repoPath) {
    // 验证路径
    if (!fs.existsSync(repoPath)) {
      error = `路径不存在：${repoPath}`;
    } else if (!fs.existsSync(path.join(repoPath, '.git'))) {
      error = `该目录不是 Git 仓库：${repoPath}`;
    } else {
      // 调用 simple-git
      const git = simpleGit(repoPath);
      try {
        const raw = await git.diff([from, to]);
        diffHtml = getPrettyHtml(raw, {
          inputFormat: 'diff',
          showFiles: true,
          matching: 'lines'
        });
      } catch (e) {
        error = `git diff 失败：${e.message}`;
      }
    }
  }

  res.render('index', {
    repoPath, from, to,
    error, diffHtml
  });
});

app.listen(3000, () => {
  console.log('服务已启动： http://localhost:3000');
});
